# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: jhkim

import datetime
import os
import pandas
import numpy
from absl import app, flags
from io import StringIO

from coin.strategy.mm.tool.feed_stat_util import enumerate_leading_digit
import coin.strategy.mm.tool.archive_base as abase
import coin.support.pta.logic.pta_stats_calculator as ptacalc


def main(_):
  tdates = abase.get_trading_dates(flags.FLAGS.trading_date)
  dfs = []
  for tdate in tdates:
    pandas.set_option("display.precision", 3)
    tdstr = tdate.strftime("%Y%m%d")
    for nametuple, df in enumerate_leading_digit(tdstr, flags.FLAGS.symbol):
      dfs.append(df[['trading_date', 'market_type', 'exchange', 'api_version', 'symbol', 'total_volume', 'vwap']])
  df = pandas.concat(dfs, axis=0).reset_index(drop=True)
  rows = []
  for _, row in df.iterrows():
    if row['total_volume'] == 0:
      continue
    row = row.copy()
    dt = datetime.datetime.strptime(row['trading_date'].strftime("%Y%m%d"), "%Y%m%d")
    row['turnover(quote)'] = ptacalc.calculate_turnover_in_quote(
        market_type=row['market_type'],
        exchange=row['exchange'],
        symbol=row['symbol'],
        volume=row['total_volume'],
        price=row['vwap'],
        current_datetime=dt)
    rows.append(row)
  print(
      pandas.DataFrame(rows).sort_values(['trading_date', 'turnover(quote)'],
      ascending=False).reset_index(drop=True))


if __name__ == '__main__':
  flags.DEFINE_string('symbol', '%', '')
  flags.DEFINE_string('trading_date', None, '')
  app.run(main)
